import React from "react";
import { BrowserRouter, useRoutes, Navigate } from "react-router-dom";
const Home = React.lazy(() => import("../views/home"));
const About = React.lazy(() => import("../views/about"));
const Detail = React.lazy(() => import("../views/detail"));
const Login = React.lazy(() => import("../views/login"));
const MainLayout = React.lazy(() => import("../views/mainLayout"));
const My = React.lazy(() => import("../views/my"));
const Publish = React.lazy(() => import("../views/publish"));

interface PropsType {
  children: JSX.Element;
}

const PrivateRouter: React.FC<PropsType> = ({ children }) => {
  const token = localStorage.getItem("token");
  if (!token) return <Navigate to="/login"></Navigate>;
  return children;
};

const routes = [
  {
    path: "/",
    element: <MainLayout></MainLayout>,
    children: [
      {
        path: "/",
        element: <Home></Home>,
      },
      {
        path: "/my",
        element: (
          <PrivateRouter>
            <My></My>
          </PrivateRouter>
        ),
      },
    ],
  },
  {
    path: "/login",
    element: <Login></Login>,
  },
  {
    path: "/detail/:id",
    element: <Detail></Detail>,
  },
  {
    path: "/publish",
    element: <Publish></Publish>,
  },
  {
    path: "/about",
    element: <About></About>,
  },
];

const Router = () => {
  const App = () => useRoutes(routes);
  return (
    <BrowserRouter>
      <App></App>
    </BrowserRouter>
  );
};

export default Router;
